package com.sgb.kjwl.view.ui.activity.self;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivitySuggestionFeedbackBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.link.entity.AreaEntity;
import com.sgb.kjwl.model.entity.Bean;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.utils.KeyboardUtils;
import com.sgb.kjwl.view.ui.activity.PhotoViewActivity;
import com.sgb.kjwl.view.ui.adapter.material.PhotoAdapter;
import com.sgb.kjwl.viewmodel.self.SuggestionFeedbackModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.DialogHelper;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;


/**
 * @版本 用户中心1.3.8
 * @产品 张彬
 * @页面 意见反馈
 * @作者 陈方凯
 */
public class SuggestionFeedbackActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    //相册选择弹窗
    private ActivitySuggestionFeedbackBinding binding;
    private PhotoAdapter mPhotoAdapter;
    //图片上传
    private List<LocalMedia> mLocalMedia = new ArrayList<>();
    private List<Bean> mUrls = new ArrayList<>();
    private List<AreaEntity> mListModelData;
    String images = "";
    @Inject
    SuggestionFeedbackModel mModel;
    private OptionsPickerView mBusinessOption;
    public int imgTotal;
    private int currentImgNum;
    private String mType;
    private int mSize = 5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    //设置状态栏为暗
    @Override
    protected boolean statusBarDark() {
        return true;
    }

    //跳转
    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, SuggestionFeedbackActivity.class);
        Bundle bundle = new Bundle();
        intent.putExtras(bundle);
        context.startActivity(intent);
    }


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(SuggestionFeedbackActivity.this, R.layout.activity_suggestion_feedback);
        //绑定ViewModel
        binding.setViewModel(mModel);
        //设置头部信息
        binding.include.titleView.setText("意见反馈");
        //返回按钮的事件
        binding.include.ivBack.setOnClickListener(this);
        binding.include.titleView.setTypeface(Typeface.DEFAULT_BOLD);
        binding.itemTvModel.setOnWholeItemClickListener(this);
        binding.nextView.setOnClickListener(this);
        binding.itemTvPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.recyclerView.setLayoutManager(new
                GridLayoutManager(SuggestionFeedbackActivity.this, 4));
        binding.recyclerView.setAdapter(mPhotoAdapter);
        mBusinessOption = new OptionsPickerBuilder(SuggestionFeedbackActivity.this, (options1, options2, options3, v) -> {
            binding.itemTvModel.setContent(mListModelData.get(options1).getSimpleName());
            mType = mListModelData.get(options1).getNo();
        }).build();

        KeyboardUtils.fixAndroidBug5497(this);
    }

    @Override
    protected void init() {
        mUrls.add(new Bean(true));
        mPhotoAdapter = new PhotoAdapter(mUrls);
        binding.recyclerView.setAdapter(mPhotoAdapter);
        initListener();
    }

    private void initListener() {
        mBusinessOption = new OptionsPickerBuilder(SuggestionFeedbackActivity.this, (options1, options2, options3, v) -> {
            binding.itemTvModel.setContent(mListModelData.get(options1).getSimpleName());
            mType = mListModelData.get(options1).getNo();
        }).setTitleText("所属板块").build();
        mPhotoAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (mPhotoAdapter.getData().get(position).isAdd) {
                return;
            }
            List<String> urls = new ArrayList<>();
            for (Bean bean : mUrls) {
                if (!bean.isAdd) {
                    urls.add(bean.url);
                }
            }
            Intent intent = new Intent(this, PhotoViewActivity.class);
            intent.putExtra(PhotoViewActivity.KEY_PHOTO_URLS, (Serializable) urls);
            intent.putExtra(PhotoViewActivity.KEY_PHOTO_POSITION, position);
            startActivity(intent);
        });
        mPhotoAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()) {
                case R.id.rl_add:
                    PictureSelector.create(this)
                            .openGallery(PictureMimeType.ofImage())
                            .loadImageEngine(GlideEngine.createGlideEngine())
                            .theme(R.style.picture_default_style)
                            .maxSelectNum(mSize)
                            .compress(true)//是否压缩
                            .minimumCompressSize(2048)//小于10M不压缩
                            .forResult(PictureConfig.CHOOSE_REQUEST);
                    break;
                case R.id.iv_delete:
                    mUrls.remove(position);
                    if (mUrls.size() == 4 && !mUrls.get(mUrls.size() - 1).isAdd) {
                        mUrls.add(new Bean(true));
                    }
                    mSize = 6 - mUrls.size();
                    mPhotoAdapter.notifyDataSetChanged();
                    break;

            }
        });
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().appComponent(appComponent).selfModule(new SelfModule(this)).build().inject(this);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片结果回调
                mUrls.remove(mUrls.size() - 1);
                for (LocalMedia localMedia : PictureSelector.obtainMultipleResult(data)) {
                    mUrls.add(new Bean(localMedia.getRealPath(), 0));
                }
                if (mUrls.size() != 5 && !mUrls.get(mUrls.size() - 1).isAdd) {
                    mUrls.add(new Bean(true));
                }
                mPhotoAdapter.notifyDataSetChanged();
                mSize = 6 - mUrls.size();
            }
        }
    }

    private void showModelPop() {
        mBusinessOption.show();
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.item_tv_model:
                if (mListModelData == null) {
                    mModel.plateSelect();
                } else {
                    showModelPop();
                }
                break;
        }
    }

    //点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.next_view:
                currentImgNum = 0;
               /* if (TextUtils.isEmpty(binding.itemTvModel.getContent())) {
                    Toast.makeText(this, "请选择所属板块!", Toast.LENGTH_SHORT).show();
                    return;
                } else */if (TextUtils.isEmpty(binding.cfkOpinion.getEditContent())) {
                    Toast.makeText(this, "请输入意见内容!", Toast.LENGTH_SHORT).show();
                    return;
                } /*else if (mUrls.size() == 1) {
                    Toast.makeText(this, "请上传图片!", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvConnect.getContent())) {
                    Toast.makeText(this, "请输入联系人!", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvPhone.getContent())) {
                    Toast.makeText(this, "请输入联系电话!", Toast.LENGTH_SHORT).show();
                    return;
                } else if (!CheckUtils.isMobileNum(binding.itemTvPhone.getContent())) {
                    Toast.makeText(this, "请输入正确的联系电话!", Toast.LENGTH_SHORT).show();
                    return;
                }*/
                DialogHelper.showProgressDialog(this, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
                if (mUrls.size() <= 1){
                    Map map = new HashMap();
                    map.put("type", mType);
                    map.put("content", binding.cfkOpinion.getEditContent());
                    //map.put("images", images);
                    map.put("contact", binding.itemTvConnect.getContent());
                    map.put("contactNumber", binding.itemTvPhone.getContent());
                    mModel.feedback(map);
                    return;
                }
                imgTotal = mUrls.get(mUrls.size() - 1).isAdd ? mUrls.size() - 1 : mUrls.size();
                mModel.uploadMutiFileModel(new File(mUrls.get(currentImgNum).url), 0, currentImgNum + 1);
                break;
        }
    }

    public void plateSelect(List<AreaEntity> data) {
        mListModelData = data;
        mBusinessOption.setPicker(mListModelData);
        showModelPop();
    }


    public void feedback() {
        Toast.makeText(this, "提交成功!", Toast.LENGTH_SHORT).show();
        finish();
    }

    //图片单张上传
    public void uploadRefresh(String url, int type) {
        images += url + ",";
        if (currentImgNum + 1 == imgTotal) {
            images = images.substring(0, images.length() - 1);
            Map map = new HashMap();
            map.put("type", mType);
            map.put("content", binding.cfkOpinion.getEditContent());
            map.put("images", images);
            map.put("contact", binding.itemTvConnect.getContent());
            map.put("contactNumber", binding.itemTvPhone.getContent());
            mModel.feedback(map);
        } else {
            System.out.println("执行次数");
            currentImgNum++;
            mModel.uploadMutiFileModel(new File(mUrls.get(currentImgNum).url), 0, currentImgNum + 1);
        }
    }
}
